$(function () {
    var queryUrl = '../spareMater/list?type=0';
    var Id = getQueryString('Id');
    if (Id) {
        queryUrl += '&Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '领料单号', name: 'materCode', align: 'center', index: 'MATER_CODE', width: 100},
            {
                label: '领料类别', align: 'center', width: 80, index: 'MATERIAL_TYPE',
                formatter: function (value, col, row) {
                    return sysEnums.MATER_TYPE[row.materialType];
                }
            },
            {label: '关联工单', name: 'jobCode', align: 'center', index: 'JOB_CODE', width: 100},
            {label: '领用部门', name: 'deptId', align: 'center', index: 'DEPT_ID', width: 120},
            {label: '领用产线', name: 'lineCode', align: 'center', index: 'LINE_CODE', width: 60},
            {label: '领料人', name: 'picker', align: 'center', index: 'PICKER', width: 80},
            {
                label: '领料时间', name: 'pickDate', align: 'center', index: 'PICK_DATE', width: 80,
                formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm');
                }
            },
            {label: '用途', name: 'purpose', align: 'center', index: 'PURPOSE', width: 120},
            // {label: '仓管员', name: 'storeker', align: 'center', index: 'STOREKER', width: 60},
            {label: '备注信息', name: 'remark', align: 'center', index: 'REMARK', width: 80},
            {
                label: '状态', align: 'center', width: 80, index: 'PROGRESS',
                formatter: function (value, col, row) {
                    return sysEnums.MATER_PROGRESS[row.progress];
                }
            },
            {
                label: '审批详情', name: 'devCode', width: 60, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>详情</button>";
                }
            },
            {
                label: '清单', width: 60, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    // flag为0时表示可以编辑，否则不可以
                    let flag = 0;
                    if (row.progress == 3 || row.progress == 2 || row.progress == 5) {
                        flag = 1;
                    }
                    // return "<button class='btn btn-outline btn-info' onclick='vm.showDetial(\"" + row.id + "\",\"" + flag + "\",\"" + row.jobCode + "\")'><i class='fa fa-file-text-o'></i>&nbsp;清单详情</button>";
                    return "<button title='清单详情' class='btn btn-outline btn-info' onclick='vm.showDetial(\"" + row.id + "\",\"" + flag + "\",\"" + row.jobCode + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: '领料单状态', name: 'progress', hidden: true},
            {label: '审核状态', name: 'isCheck', hidden: true}
        ]
    });
    vm.getTreeListDept();
    vm.getTreeList();
    vm.loadApproverList();
});
$(function (){
    //获取对象的值
    var arrays = Object.entries(sysEnums.MATER_TYPE);
    arrays.forEach(function (item){
        vm.materiaTyppeList.push({
            name:item[1],
            value:item[0]
        })
    })
})

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    callback: {
        beforeCheck: true
    }

};

var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};
function outTreeCheck(e, treeObj, treeNode) {


    // vm.query();
}

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        materialBase: {
            remark: '',
            type: 0,
            jobCode: '',
            storeker: '',
            approveDate: '',
            approver: '',
            pickDate: '',
            picker: '',
            purpose: '',
            deptId: '',
            isCheck: 0,
            isOk: 0,
            checkRemark: '',
            id: '',
            materialType: '' // 领料单类别
        },
        ruleValidate: {
            purpose: [
                {required: true, message: '用途不能为空', trigger: 'blur'}
            ]
        },
        repairStartRange: [], // 维修开始查询时间区间
        q: {
            startTime:'',
            endTime:'',
            materCode: '',
            jobCode: '',
            progress: '',
            deptId:'',
            picker: '',
            materialType:''//领料类别
        },
        treeList: [],//设备组织树列表
        workShopShow: '',//车间显示值
        approverList: [], // 领料单审批人员列表
        approveParam: {
            id: '', // 物件领料单ID
            approverId: '' // 审批用户ID
        },
        auditTableColumns: [
            {
                title: '环节名称',
                key: 'workitemName',
                width: 190
            },
            {
                title: '审批状态',
                key: 'state',
                width: 100,
                render: (h, params) => {
                    return sysEnums.OA_CHECK_FLAG[params.row.state];
                }
            },
            {
                title: '审批人',
                key: 'approverName',
                width: 100
            },
            {
                title: '审批时间',
                key: 'approveDate',
                width: 150
            },
            {
                title: '审批备注',
                key: 'remark',
                width: 150
            }
        ],
        auditTableData: [], // 审批table数据
        checkList: enumsToList('MATER_CHECK_FLAG'),//领料单审批状态
        okList: enumsToList('MATER_FLAG'),//领料单完成状态
        materTypes: enumsToList('MATER_TYPE'),//领料单类别
        materProgress: enumsToList('MATER_PROGRESS'),//领料单状态
        line: '',// 产线信息，线边库时显示用
        materiaTyppeList:[]
    },
    methods: {
        deptTree: function (param) {
            console.log()
            openWindow({
                title: "请选择设备组织结构",
                area: ['300px', '500px'],
                content: jQuery("#workShopSubmit"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = deptZtree.getSelectedNodes();
                    //设置车间显示值
                    vm.q.deptId = node[0].deptId;
                    vm.workShopShow = node[0].complexName;
                    layer.close(index);
                }
            });
        },
        getTreeListDept: function () {
            Ajax.request({
                url: '../sys/user/treeDeptBySCXLevel?level=2',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                    deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, vm.treeList);
                    // 默认展开工厂一级
                    deptZtree.expandNode(deptZtree.getNodeByParam("deptId", '01', null));
                }
            });
        },
        //故障处理
        troubleshooting:function (){
            var _this =this;
            let ids = getSelectedRow("#jqGrid");
            if (ids == null) {
                return;
            }
            let row = getSelectedRowData("#jqGrid");
            if(row.progress != '2'){
                alert('只能处理审核中的领料单！')
                return;
            }
            confirm('是否确认处理该条数据', function () {
                // 领料单编制完毕，提交审核
                Ajax.request({
                    url: "../spareMater/checkOver?id=" + ids,
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('提交成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        //审核详情
        shviewOption: function (res) {
            let data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysoaprocess/queryAll',
                params: {busId: data.id, busType: 'MATERIAL'},
                type: 'POST',
                successCallback: function (res) {
                    vm.auditTableData = res.list;
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['700px', '480px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('#auditHistoryArea')
                    });
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.line = '';
            vm.materialBase = {
                id: '',
                type: 0, // 备件领料单
                materialType: 2, // 领料单类型，默认日常领料
                lineCode: '', // 产线编码
                jobCode: '',
                purpose: '',
                remark: ''
            };
            vm.getTree();
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var row = getSelectedRowData("#jqGrid");
            var isCheck = row.isCheck;
            if (isCheck == 1) {
                alert("当前审核已通过禁止修改！");
            } else {
                vm.showList = false;
                vm.title = "修改";
                vm.getInfo(id);
                vm.getTree();
            }
        },
        saveOrUpdate: function (event) {
            /*
            添加必填校验
            * */
            if (vm.materialBase.materialType==3){
                if(!vm.materialBase.jobCode){
                    alert('请选择维护工单！')
                    return
                }
            }else if(vm.materialBase.materialType==2){
                if(!vm.materialBase.jobCode){
                    alert('请选择维修工单！')
                    return
                }
            }else if(vm.materialBase.materialType==1){
                if(!vm.materialBase.lineCode){
                    alert('请选择产线！')
                    return
                }
            }
            let url = vm.materialBase.id == (null || '') ? "../spareMater/save" : "../spareMater/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.materialBase),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        /*领料单无效的方法*/
        invalid: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            let params = getSelectedRowData("#jqGrid");
            let progress = params.progress;
            if(progress != 5){
                alert('只有出库完毕的工单才可以无效！')
                return;
            }
            confirm('确定要废除此工单吗？', function () {
                Ajax.request({
                    url: "",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../spareMater/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../spareMater/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.materialBase = r.materialBase;
                    vm.line = r.materialBase.line;
                }
            });
        },
        loadApproverList: function (id) {
            // 加载审批人员列表，一般为当前提交人所在部门的室主任
            Ajax.request({
                url: "../sys/user/spareApproverList",
                async: true,
                successCallback: function (r) {
                    vm.approverList = r.approverList;
                }
            });
        },
        commit: function () {
            let _this = this;
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress != '1' && data.progress != '4') {
                iview.Message.error("只有新建或审核驳回的领料单才可以提交审核!");
                return;
            }
            // 赋值
            this.approveParam.id = id;
            //任务指派后工单状态变为维修中
            openWindow({
                title: "选择审批人员",
                area: ['400px', '250px'],
                content: jQuery("#audit"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    layer.close(index);
                    // 领料单编制完毕，提交审核
                    Ajax.request({
                        url: "../spareMater/commitApprove",
                        params: JSON.stringify(_this.approveParam),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('提交成功', function (index) {
                                vm.reload();
                            });
                        }
                    });

                }
            });
        },
        cancel: function () {
            let _this = this;
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress == '5' || data.progress == '6' || data.progress == '7') {
                iview.Message.error("领料单已出库、已关闭或已取消，请勿重复操作！");
                return;
            }
            confirm('确定要取消领料[' + data.materCode + ']?', function () {
                // 领料单编制完毕，提交审核
                Ajax.request({
                    url: "../spareMater/cancel?id=" + id,
                    params: JSON.stringify(_this.approveParam),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('提交成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        outMater: function () {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress != '3') {
                iview.Message.error("只有处于[待出库]状态的领料单才可以执行出库!");
                return;
            }
            //出库操作
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 领料清单',
                content: '../spare/outList.html?id=' + id,
                btn: ['出库', '取消'],
                btn1: function (index) {
                    //出库处理
                    Ajax.request({
                        url: "../spareMater/out/" + id,
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('出库成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                    layer.close(index);
                }
            })
        },

        showDetial: function (id, flag, jobCode) {
            // var id = row.id;
            // var gdbh = row.jobCode;
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-file-text-o"></i> 备件清单',
                content: '../spare/sparematerialrecord.html?materId=' + id + '&gdbh=' + jobCode + '&flag=' + flag,
            })
        },
        handleRepairStartRangeChange(dateVal, dateType) {
            this.q.startTime = dateVal[0];
            this.q.endTime = dateVal[1];
        },
        reload: function (event) {
            vm.showList = true;
            if (this.q.startTime) {
                this.q.startTime = gmt2DateStr(this.q.startTime);
            }
            if (this.q.endTime) {
                this.q.endTime = gmt2DateStr(this.q.endTime);
            }
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                search: true,
                postData: vm.q,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                materCode: '',
                jobCode: '',
                startTime: '',
                endTime: '',
                progress: '',
                deptId:'',
                picker: '',
                materialType:''
            };
            this.workShopShow = '';
            this.repairStartRange = [];
            vm.reload();
            deptZtree.cancelSelectedNode();
        },
        // 获取设备维修工单列表
        getRepairJobCodeSelect: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择工单编号',
                content: '../spare/sparematerialbaseSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.materialBase.jobCode = res.repairCode;
                        vm.materialBase.purpose = res.devName+'备件更换';
                    }
                }
            })
        },
        // 获取设备临时维护工单列表
        getMaintenanceJobCodeSelect: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择工单编号',
                content: '../spare/sparematerialbaseMaintenanceSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.materialBase.jobCode = res.repairCode;
                    }
                }
            })
        },
        loadLineList: function () {
            openWindow({
                title: "选择产线",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes = ztree.getSelectedNodes();
                    if (nodes.length == 0 || nodes[0].deptLevel != 3) {
                        alert("请选择产线");
                        return;
                    }
                    layer.close(index);
                    vm.line = nodes[0].complexName;
                    vm.materialBase.lineCode = nodes[0].dcode;
                }
            });
        },
        getTree: function () {
            //加载分类树
            ztree = $.fn.zTree.init($("#categoryTree"), setting, vm.treeList);
            ztree.expandAll(true);
        },
        getTreeList: function () {
            Ajax.request({
                url: '../sys/user/loadLineList',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                }
            });
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});
